﻿using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HiauPdm.Bll
{
    /// <summary>
    /// 业务层全局通用类
    /// </summary>
    public static class BGlobal
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        internal static readonly string DbConnString;

        /// <summary>
        /// 文件存储位置
        /// </summary>
        public static readonly string AttachmentPath;

        /// <summary>
        /// 应用系统标题
        /// </summary>
        public static readonly string SystemName;

        /// <summary>
        /// 版权信息(中文)
        /// </summary>
        public static readonly string SystemCopyrightC;

        /// <summary>
        /// 版权信息(英文)
        /// </summary>
        public static readonly string SystemCopyrightE;

        /// <summary>
        /// 加密的密钥(8位)
        /// </summary>
        public const string Encrypt_Key = "Hiau_Erp";

        /// <summary>
        /// 构造函数
        /// </summary>
        static BGlobal()
        {
            DbConnString = Decrypt(ConfigurationManager.AppSettings["DbConnString"], Encrypt_Key);
            AttachmentPath = Decrypt(ConfigurationManager.AppSettings["AttachmentPath"], Encrypt_Key);
            SystemName = Decrypt(ConfigurationManager.AppSettings["SystemName"], Encrypt_Key);
            SystemCopyrightC = Decrypt(ConfigurationManager.AppSettings["SystemCopyrightC"], Encrypt_Key);
            SystemCopyrightE = Decrypt(ConfigurationManager.AppSettings["SystemCopyrightE"], Encrypt_Key);
        }

        /// <summary>
        /// 字符串加密
        /// </summary>
        public static string Encrypt(string pToEncrypt, string pDesKey)
        {
            string strEncrypt;
            try
            {
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                byte[] desKeyByte = new byte[] { 1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80 };
                Array.Copy(Encoding.ASCII.GetBytes(pDesKey), desKeyByte, (Encoding.ASCII.GetBytes(pDesKey).Length < 8) ? Encoding.ASCII.GetBytes(pDesKey).Length : 8);
                using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                {
                    des.Key = desKeyByte;
                    des.IV = (byte[])desKeyByte.Clone();
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                        }
                        StringBuilder strDes = new StringBuilder("$");
                        foreach (byte b in ms.ToArray())
                        {
                            strDes.AppendFormat("{0:X2}", b);
                        }
                        strEncrypt = strDes.ToString();
                    }
                }
            }
            catch
            {
                strEncrypt = null;
            }
            return strEncrypt;
        }

        /// <summary>
        /// 字符串解密
        /// </summary>
        public static string Decrypt(string pToDecrypt, string pDesKey)
        {
            string strDecrypt;
            try
            {
                if (pToDecrypt.Substring(0, 1) != "$")
                {
                    strDecrypt = pToDecrypt;
                }
                else
                {
                    byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                    for (int x = 0; x < (pToDecrypt.Length / 2); x++)
                    {
                        int i = Convert.ToInt32(pToDecrypt.Substring((x * 2) + 1, 2), 0x10);
                        inputByteArray[x] = (byte)i;
                    }
                    byte[] desKeyByte = new byte[] { 1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80 };
                    Array.Copy(Encoding.ASCII.GetBytes(pDesKey), desKeyByte, (Encoding.ASCII.GetBytes(pDesKey).Length < 8) ? Encoding.ASCII.GetBytes(pDesKey).Length : 8);
                    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                    {
                        des.Key = desKeyByte;
                        des.IV = (byte[])desKeyByte.Clone();
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                            {
                                cs.Write(inputByteArray, 0, inputByteArray.Length);
                                cs.FlushFinalBlock();
                            }
                            strDecrypt = Encoding.Default.GetString(ms.ToArray());
                        }
                    }
                }
            }
            catch
            {
                strDecrypt = pToDecrypt;
            }
            return strDecrypt;
        }

        /// <summary>
        /// 判断是否为数值字符串
        /// </summary>
        public static bool IsNumeric(string sNum)
        {
            if ((sNum == null) || (sNum == string.Empty))
            {
                return false;
            }
            char[] cNum = sNum.ToCharArray();
            for (int i = 0; i < cNum.Length; i++)
            {
                if ((cNum[i] < '0') || (cNum[i] > '9'))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 生成SQL模糊查询语句
        /// </summary>
        public static string BuildLike(string sWhere, params string[] sFields)
        {
            string sSqlWhere = string.Empty;
            string[] sWheres = sWhere.Split(new string[] { " ", "　", "\t" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < sWheres.Length; i++)
            {
                if (i == 0) { sSqlWhere += "("; }
                else
                {
                    sSqlWhere += " AND ";
                }
                for (int j = 0; j < sFields.Length; j++)
                {
                    if (j == 0) { sSqlWhere += "("; }
                    else
                    {
                        sSqlWhere += " OR ";
                    }
                    sSqlWhere += string.Format("{0} LIKE '%{1}%'", sFields[j], sWheres[i]);
                    if (j == sFields.Length - 1) { sSqlWhere += ")"; }
                }
                if (i == sWheres.Length - 1) { sSqlWhere += ")"; }
            }
            if (sSqlWhere != string.Empty)
            {
                return sSqlWhere;
            }
            else
            {
                return "1=1";
            }
        }

        /// <summary>
        /// 普通字符串转16进制字符串
        /// </summary>
        public static string StringToHex(string str)
        {
            if (str == null || str.Length <= 0) { return string.Empty; }
            string strHex = "";
            byte[] bytes = Encoding.Default.GetBytes(str);
            for (int i = 0; i < bytes.Length; i++)
            {
                strHex += bytes[i].ToString("X2");
            }
            return strHex;
        }

        /// <summary>
        /// 16进制字符串转普通字符串
        /// </summary>
        public static string HexToString(string strHex)
        {
            if (strHex == null || strHex.Length % 2 != 0) { return string.Empty; }
            byte[] bytes = new byte[strHex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16);
            }
            return Encoding.Default.GetString(bytes);
        }
    }
}
